// 评论节点类型
import type { CommentVO } from "@/types/vo/CommentVO";

// 扁平化后的评论类型
export interface FlatComment {
  id: number
  momentId: number
  replyType: number
  content: string
  toName: string
  toAvatar: string
  parentId: number
  userName: string
  avatar: string
  createdTime: number
  nodeId: number
  nodePId: number
  replies?: FlatReply[]
  picUrlList?: string[] // 修改为picUrlList
}

// 扁平化后的回复类型
export interface FlatReply {
  id: number
  momentId: number
  replyType: number
  content: string
  fromId: string
  toId: string
  toName: string
  toAvatar: string
  parentId: number
  userName: string
  avatar: string
  createdTime: number
  nodeId: number
  nodePId: number
  rootCommentId?: number // 保存一下该回复的根评论的 id， 后续是否显示回复看这个
  picUrlList?: string[] // 修改为picUrlList
}

/**
 * 递归函数：将所有层级的回复平铺到同一数组中
 * @param children 当前层级的 children 数组
 * @param rootCommentId 根节点的 id，用于标记所有回复的来源
 * @returns 扁平化后的 FlatReply 数组
 */
function flattenReplies(children: CommentVO[], rootCommentId: number): FlatReply[] {
  let replies: FlatReply[] = []
  for (const child of children) {
    const reply: FlatReply = {
      id: child.id,
      momentId: child.momentId,
      replyType: child.replyType,
      content: child.content,
      fromId: child.fromId || '',
      toId: child.toId || '',
      toName: child.toName,
      toAvatar: child.toAvatar,
      parentId: child.parentId,
      userName: child.userName,
      avatar: child.avatar,
      createdTime: child.createdTime,
      nodeId: child.nodeId,
      nodePId: child.nodePId,
      rootCommentId: rootCommentId,
      picUrlList: child.picUrlList // 修改为picUrlList
    }
    replies.push(reply)
    if (child.children && child.children.length > 0) {
      // 递归处理子节点，并将结果拼接到 replies 中
      replies = replies.concat(flattenReplies(child.children, rootCommentId))
    }
  }
  return replies
}

/**
 * 扁平化评论树，将根节点的所有子节点（所有层级）都放入 replies 中
 * @param comments 原始评论数组
 * @returns 扁平化后的评论数组
 */
export function flattenComments(comments: CommentVO[]): FlatComment[] {
  return comments.map(comment => {
    const flatComment: FlatComment = {
      id: comment.id,
      momentId: comment.momentId,
      replyType: comment.replyType,
      content: comment.content,
      toName: comment.toName,
      toAvatar: comment.toAvatar,
      parentId: comment.parentId,
      userName: comment.userName,
      avatar: comment.avatar,
      createdTime: comment.createdTime,
      nodeId: comment.nodeId,
      nodePId: comment.nodePId,
      picUrlList: comment.picUrlList // 修改为picUrlList
    }
    if (comment.children && comment.children.length > 0) {
      flatComment.replies = flattenReplies(comment.children, comment.id)
    }
    return flatComment
  })
}
